﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Role;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Role
{
    public class AddRoleHandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public AddRoleHandler(IBaseRepository<RoleModel> roleRepo,IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var role = roleRepo.GetAll().Where(x => x.RoleName == request.RoleName&&x.IsDelete==false).FirstOrDefault();
            if (role!=null)
            {
                res.Msg = "角色名称已存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var roles = mapper.Map<RoleModel>(request);
            roles.CreateName = "张三";
            roles.CreateTime = DateTime.Now;
            var i = roleRepo.Add(roles);
            if (i>0)
            {
                res.Msg = "添加成功";
                res.Code = ApiEnum.Success;
                res.Data = i;
            }
            else
            {
                res.Msg = "添加失败";
                res.Code = ApiEnum.Error;
                res.Data = i;
            }
            return Task.FromResult(res);
        }
    }
}
